﻿using System;
using static CyberU;
using static CyberU.UI;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using Random = UnityEngine.Random;

public class Repulsion : MonoBehaviour
{
    public Rigidbody2D rigidbody;
    private static float repulsionForce = 5f;
    [Tooltip("当两个物体中心距离小于该值时，视为重合，使用默认方向")]
    public float minDistance = 0.01f;

    public void Awake()
    {
        rigidbody=GetOrAddComponent<Rigidbody2D>(gameObject);
    }

    public void OnTriggerStay2D(Collider2D other)
    {
        // Delog("OnTriggerStay2D");
        Rigidbody2D otherRb = other.GetComponent<Rigidbody2D>();
        if (otherRb == null) return;
        Vector2 position = (Vector2)transform.position;
        Vector2 otherPosition = (Vector2)other.transform.position;
        Vector2 direction;
        float distance = Vector2.Distance(position, otherPosition);
        if (distance <= minDistance)
        {
            direction = RandomDirection().normalized;
        }
        else
        {
            direction = (otherPosition - position).normalized;
            direction += 0.01f * RandomDirection();
            direction = direction.normalized;
        }
        rigidbody.AddForce(-direction * repulsionForce, ForceMode2D.Impulse);
    }

    public static Vector2 RandomDirection()
    {
        float angle = Random.Range(0f, 360f);
        float radians = angle * Mathf.Deg2Rad;
        // Delog($"{radians}");
        return new Vector2(
            Mathf.Cos(radians),
            Mathf.Sin(radians)
        );
    }
}